import React, { useState, useEffect } from 'react';
import { obj_str, ck_empty, NuiDlg, Input, ErrView, BaseDlg, NuiBt, uPlc } from 'sui';
import { g_line, g_wsn } from 'db/state';
import { get_gun, clear_gun } from 'base/api';

const DlgCode = ({ open, setOpen, hcmd }) => {
    const [code, setCode] = useState("");
    const [err, setErr] = useState("");

    const hcode = (v) => {
        const tmp = v.split("#");
        if (tmp.length !== 7) {
            setErr("编码格式错误")
            return;
        }

        setOpen(false);
        hcmd(tmp);
    };

    useEffect(() => {
        if (!open) {
            return;
        }

        const id = setInterval(() => {
            uPlc(null, "get",
                {
                    line: g_line(),
                    sn: g_wsn(),
                },
                r => {
                    const ret = get_gun(r);
                    if (!ret) {
                        return;
                    }

                    setCode(ret);
                    clear_gun();

                    hcode(ret);
                },
                e => setCode(null));
        }, 700);

        return () => clearInterval(id);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open]);

    return (
        <BaseDlg open={open} title="扫码">
            <ErrView err="请用扫枪扫描物料二维码" tp="info"/>
            <div className="ml-4 text-2xl">{code}</div>
            <div className="inline-flex justify-end">
                <NuiBt hcmd={() => setOpen(false)} className="mr-4 mb-3">取消</NuiBt>
            </div>
            <ErrView err={err}/>
        </BaseDlg>
    );
};

const ck_int = (v, pre) => {
    if (!v) {
        return pre + "不能为空";
    }

    const tmp = parseInt(v, 10);
    if (isNaN(tmp)) {
        return pre + "必须为数字";
    }

    if (tmp <= 0) {
        return pre + "必须大于0";
    }
};

const DlgSide = ({ open, setOpen, hcmd, cur }) => {
    const [err, setErr] = useState();
    const [num, setNum] = useState();
    const [pos, setPos] = useState();

    useEffect(() => {
        if (!open) {
            return;
        }

        setErr("");
        setNum("");
        setPos(obj_str(cur, "pos"));
    }, [open, cur]);

    const herr = (e) => {
        setErr(e);
    };

    const hdone = () => {
        let e = ck_int(num, "数量");
        if (e) {
            return herr(e);
        }

        e = ck_empty(pos, "仓位");
        if (e) {
            return herr(e);
        }

        setOpen(false);

        hcmd({
            num: num,
            pos: pos,
        });
    };

    return (
        <NuiDlg open={open} title="退料数量" hcmd={hdone} labd="确定" hcancel={() => setOpen(false)}>
            <div className="flex flex-col">
                <Input label="数量" value={num} setValue={setNum} name="num"/>
                <Input label="仓位" value={pos} setValue={setPos} name="pos"/>
            </div>
            <ErrView err={err}/>
        </NuiDlg>
    );
};

export {DlgSide, DlgCode};
